package codepulse.blogmoon.cn.system.controller;

import codepulse.blogmoon.cn.common.entity.Result;
import com.google.common.collect.Lists;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {


    @Value("${qiniu.access-key}")
    private String accessKey;

    @Value("${qiniu.secret-key}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file, @RequestParam("url") String url) throws IOException {
        String path = uploadImageQiniu(file, url);
        return Result.success(path);
    }

    @PostMapping("/batch/upload")
    public Result upload(@RequestParam("files") MultipartFile[] files, @RequestParam("url") String url) throws IOException {
        List<String> pathList = Lists.newArrayList();
        for (MultipartFile file : files) {
            String path = uploadImageQiniu(file, url);
            pathList.add(path);
        }
        return Result.success(pathList);
    }


    private String uploadImageQiniu(MultipartFile multipartFile, String url) {
        try {
            //1、获取文件上传的流
            byte[] fileBytes = multipartFile.getBytes();
            //2、创建日期目录分隔
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());

            //3、获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = url + "/" + datePath + "/" + UUID.randomUUID().toString().replace("-", "") + suffix;

            //4.构造一个带指定 Region 对象的配置类
            Configuration cfg = new Configuration();
            UploadManager uploadManager = new UploadManager(cfg);

            //5.获取七牛云提供的 token
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            uploadManager.put(fileBytes, filename, upToken);
            return filename;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
